package settings;

import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.imstlife.vending.R;
import com.imstlife.vending.adapter.WiFiItemAdapter;
import com.imstlife.vending.utils.WifiConnector;
import com.imstlife.vending.utils.WifiSearcher;
import com.imstlife.vending.utils.WifiUtils;

import java.util.ArrayList;
import java.util.List;

public class NewWiFiFragment extends Fragment {

	private static String TAG = "WiFiFragment";

	private TextView currentTextView;
	/** 打开关闭提示 */
	private TextView tipTextView;
	/** 打开关闭开关 */
	private Switch wifiSwitch;

	private String wifiPassword = null;

	private WifiUtils wifiUtils;

	private ListView listView;
	private List<ScanResult> wifiResultList;
	private List<String> securityModeList;
	private WiFiItemAdapter wiFiItemAdapter;

	private WifiSearcher wifiSearcher;
	private WifiConnector wifiConnector;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootLayout = inflater.inflate(R.layout.fragment_wifi, container,
				false);

		currentTextView = (TextView) rootLayout
				.findViewById(R.id.fragment_wifi_current);
		tipTextView = (TextView) rootLayout
				.findViewById(R.id.fragment_wifi_tip);

		wifiSwitch = (Switch) rootLayout
				.findViewById(R.id.fragment_wifi_switch);

		listView = (ListView) rootLayout.findViewById(R.id.fragment_wifi_list);
		listView.setOnItemClickListener(new ListOnItemClickListener());

		securityModeList = new ArrayList<String>();

		wifiSearcher = new WifiSearcher(getActivity(),
				new MySearchWifiListener());
		wifiConnector = new WifiConnector(getActivity(),
				new MyWifiConnectListener());

		wifiUtils = new WifiUtils(getActivity());

		// 检查WiFi开关状态
		if (wifiUtils.checkWiFiState() == WifiConfiguration.Status.DISABLED) {
			wifiSwitch.setChecked(false);

			tipTextView.setVisibility(View.VISIBLE);
			tipTextView.setText(R.string.please_open_wlan);
			listView.setVisibility(View.INVISIBLE);
		} else {
			tipTextView.setVisibility(View.INVISIBLE);
			listView.setVisibility(View.VISIBLE);

			wifiSwitch.setChecked(true);

			wifiSearcher.search();
		}

		wifiSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked == true) {
					tipTextView.setText(R.string.openning_wlan);

					Log.e(TAG, "dakai");
					wifiSearcher.search();
				} else {
					tipTextView.setVisibility(View.VISIBLE);
					tipTextView.setText(R.string.please_open_wlan);
					listView.setVisibility(View.INVISIBLE);

					wifiUtils.WifiClose();
					// 通知adapter刷新数据
					wiFiItemAdapter.notifyDataSetInvalidated();
					Log.e(TAG, "guanbi");
				}
			}
		});

		return rootLayout;
	}

	 class MySearchWifiListener implements WifiSearcher.SearchWifiListener {

		@Override
		public void onSearchWifiFailed(WifiSearcher.ErrorType errorType) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onSearchWifiSuccess(List<ScanResult> scanResults) {
			// TODO Auto-generated method stub
			Log.e(TAG, wifiUtils.getConnectedSSID());

			wifiResultList = scanResults;

			// 提取扫描结果
			List<String> ssidResults = new ArrayList<String>();

			for (ScanResult scanResult : scanResults) {

				int networkId = wifiUtils.isConfiguration("\""
						+ scanResult.SSID + "\"");

				System.out.println(scanResult.SSID + "--" + networkId + "--"
						+ scanResult.capabilities);

				ssidResults.add(scanResult.SSID);

				if (scanResult.capabilities.indexOf("ESS") != -1
						&& scanResult.capabilities.indexOf("WPA") == -1) {
					securityModeList.add("无密码");
				} else if (scanResult.capabilities.indexOf("WPA") != -1) {
					securityModeList.add("通过WPA进行保护");
				} else {
					securityModeList.add(scanResult.SSID);
				}

			}

			currentTextView.setText("当前连接：" + wifiUtils.getConnectedSSID());

			tipTextView.setVisibility(View.INVISIBLE);
			listView.setVisibility(View.VISIBLE);

			wiFiItemAdapter = new WiFiItemAdapter(getActivity(), scanResults,
					securityModeList);
			listView.setAdapter(wiFiItemAdapter);
		}
	}

	class MyWifiConnectListener implements WifiConnector.WifiConnectListener {

		@Override
		public void OnWifiConnectCompleted(boolean isConnected) {
			// TODO Auto-generated method stub
			if (isConnected) {
				System.out.println("yes");
			} else {
				System.out.println("no");
			}

		}
	}

	class ListOnItemClickListener implements OnItemClickListener {
		String wifiItemSSID = null;

		@Override
		public void onItemClick(AdapterView<?> arg0, View view,
				final int position, long arg3) {

			final ScanResult scanResult = wifiResultList.get(position);

			String securityMode = securityModeList.get(position);
			
			Log.e(TAG, "当前点击的安全模式" + securityMode);

			int networkId = wifiUtils.isConfiguration("\"" + scanResult.SSID
					+ "\"");

			Log.e(TAG, "当前点击的networkID" + networkId);

			// 之前已经配置好，即之前连接过
			if (networkId != -1) {
				wifiUtils.connectWifiWith(networkId);

			} else if (securityMode.equals("无密码")) {

				wifiConnector.connect(scanResult.SSID, "", WifiConnector.SecurityMode.OPEN);
			} else {
				WifiPswDialog pswDialog = new WifiPswDialog(getActivity(),
						new WifiPswDialog.OnCustomDialogListener() {
							@Override
							public void back(String str) {
								// TODO Auto-generated method stub
								wifiPassword = str;
								if (wifiPassword != null) {

									wifiConnector.connect(scanResult.SSID,
											wifiPassword, WifiConnector.SecurityMode.WPA2);
									// int netId = wifiUtils.AddWifiConfig(
									// wifiResultList, scanResult.SSID,
									// wifiPassword);
									// Log.i("WifiPswDialog",
									// String.valueOf(netId));
									// if (netId != -1) {
									// wifiUtils.getConfiguration();// 重新获取配置信息
									// if (wifiUtils.connectWifiWith(netId)) {
									//
									// if (connectedFlag != -1) {
									// securityModeList.set(
									// connectedFlag, "已保存");
									//
									// }
									//
									// securityModeList.set(position,
									// "已连接");
									// connectedFlag = position;
									//
									// }
									// } else {
									// T.showShort(getActivity(), "网络连接错误");
									// }

								} else {
								}
							}
						});
				pswDialog.show();
			}
		}
	}

	// ScanResult类型转为String
	public void scanResultToString(List<ScanResult> listScan,
			List<String> listStr) {
		Log.e(TAG, wifiUtils.getConnectedSSID());
		for (int i = 0; i < listScan.size(); i++) {
			ScanResult strScan = listScan.get(i);

			String str;
			if (strScan.SSID.equals(wifiUtils.getConnectedSSID())) {
				str = strScan.SSID + "--已连接";
			} else {
				str = strScan.SSID + "--" + strScan.BSSID
						+ strScan.capabilities;
			}

			boolean bool = listStr.add(str);
			if (bool) {
				wiFiItemAdapter.notifyDataSetInvalidated();
			} else {
				Log.i("scanResultToSting", "fail");
			}
			Log.i("scanResultToString", listStr.get(i));
		}
	}
}
